package com.yzzrjy.util;

public class IDGenerator{
    public static IDGenerator mInstance;
    private final long START_TIME = 1674391084L;
    private final long SEQUENCE_BIT = 10; //序列号占用的位数
    private final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    private long sequence = 0L; //序列号
    private long lastTime = -1L;//上一次时间戳

    public synchronized static IDGenerator getInstance(){
        if (mInstance == null) {
            mInstance = new IDGenerator();
        }
        return mInstance;
    }

    public synchronized long nextId() {
        long currTime = getNewTime();
        if (currTime < lastTime) {
            throw new RuntimeException("Refusing to generate id");
        }
        if (currTime == lastTime) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                throw new RuntimeException("too much id in 1 second");
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastTime = currTime;
        return (currTime - START_TIME) << SEQUENCE_BIT //时间戳部分
                | sequence;                            //序列号部分
    }

    private long getNewTime() {
        return System.currentTimeMillis() / 1000;
    }

}